package com.caochenlei.tree.ufs.version2;

public class UnionFindSets {
    private int[] eleAndGroup;      //记录结点元素及分组的标识符
    private int count;              //记录并查集中数据的分组个数

    public UnionFindSets(int N) {
        this.count = N;
        this.eleAndGroup = new int[N];
        for (int i = 0; i < eleAndGroup.length; i++) {
            eleAndGroup[i] = i;
        }
    }

    //获取并查集中有多少分组
    public int count() {
        return count;
    }

    //元素p所在分组的标识符
    public int find(int p) {
        while (true) {
            if (p == eleAndGroup[p]) {
                return p;
            }
            p = eleAndGroup[p];
        }
    }

    //查询元素p和元素q是否属于同一组
    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    //合并元素p和元素q所在组为同一组
    public void union(int p, int q) {
        //找到p元素和q元素所在组对应的树的根结点
        int pRoot = find(p);
        int qRoot = find(q);
        //如果p和q已经在同一分组，则不需要合并了
        if (pRoot == qRoot) {
            return;
        }
        //p所在树根结点的父结点为q所在树的根结点
        eleAndGroup[pRoot] = qRoot;
        //组的数量-1
        this.count--;
    }
}
